package com.yao.securitydemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yao.securitydemo.entity.Users;
import com.yao.securitydemo.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author tututu
 * @description
 * @date 2022/4/22 23:58
 */
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = usersMapper.selectOne(new QueryWrapper<Users>().lambda().eq(Users::getUsername, username));
        if (users==null){
            throw new UsernameNotFoundException("用户不存在");
        }

        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN,ROLE_SALE");
        return new User(users.getUsername(),users.getPassword(), list);
    }
}
